<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 小程序公共API服务
 */
namespace app\ais\controller\api\v1;
use app\ais\controller\api\Base;
use app\ais\model\AisInfoCate;
use app\ais\model\AisInfo;
use app\ais\model\AisInfoReply;
use app\ais\model\AisInfoFollow;
use app\ais\model\AisConfig;
use app\ais\model\AisInfoMp;
use app\ais\model\MchId;
use app\common\facade\WechatPay;
use app\common\facade\Upload;
use app\common\model\SystemUser;
use app\common\model\SystemMemberSms;
use think\facade\Config;
use filter\Filter;

class Infosend extends Base{

   /**
     * 初始化当前应用是否登录
     * @return void
     */
    public function initialize() {
        parent::initialize();
        $this->isUserAuth();
    }

    /**
     * 判断是否注册城市号
     */
    public function isMp(){
        $rel = AisInfoMp::where(['uid' => $this->user->id])->count();
        if($rel){
            return enjson(200);
        }
        return enjson(204);
    }
    
    /**
     * 判断是否注册城市号
     */
    public function getThemes(){
        $rel = AisInfoCate::where(['member_miniapp_id' => $this->member_miniapp_id])->field('id,name')->select();
        return enjson(200,$rel);
    }

    /**
     * 读取微信API
     * @param integer 读取ID
     * @return json
     */
    public function getTpl(){
        $param['id'] = $this->request->param('id/d',0);
        $this->apiSign($param);
        $rel = AisInfoCate::cateTpl($param['id']);
        return enjson(200,'成功',$rel);
    } 

    /**
     * 城市号信息
     */
    public function getMp(){
        $param['uid'] = $this->request->param('uid/d',0);
        $this->apiSign($param);
        $where = [];
        $where['uid'] = $param['uid'];
        $rel = AisInfoMp::where($where)->find();
        if($rel){
            if($rel->is_lock){
                return enjson(403,'城市号不存在');
            }
            $rel->views = AisInfo::where(['uid' => $rel->uid])->count();
            $rel->like  = AisInfoFollow::where(['uid' => $rel->uid])->count();
            $rel->is_follow =  0;
            $rel->vip_time = empty($rel->vip_time)?'0':date('Y-m-d',$rel->vip_time);
            $rel->reg_time = empty($rel->reg_time)?'0':date('Y-m-d',$rel->reg_time);
            if($this->user){
                $rel->is_follow = AisInfoFollow::where(['uid' => $this->user->id,'like_uid'=>$rel->uid])->count();
            }
            return enjson(200,'成功',$rel);
        }
        return enjson(204);
    }

    /**
     * 编辑开通城市号和申请认证城市号
     *
     * @return void
     */
    public function editMp(){
        $param['logo']      = $this->request->param('logo/s');
        $param['skin']      = $this->request->param('skin/s');
        $param['title']     = $this->request->param('title/s');
        $param['note']      = $this->request->param('note/s');
        $param['telphone']  = $this->request->param('telphone/s');
        $param['vip_title'] = $this->request->param('vip_title/s','');
        $param['vip_about'] = $this->request->param('vip_about/s','');
        $param['checked']   = $this->request->param('checked/d',0);
        $this->apiSign($param);
        $data['title'] = $param['title'];
        $data['note']  = $param['note'];
        $rel = AisInfoMp::where(['uid' => $this->user->id])->find();
        if($rel){
            if($rel->is_lock){
                return enjson(403,'城市号已被锁定');
            }
            //判断是否修改skin
            if(!empty($param['skin'])){
                $rel->skin = $param['skin'];
            }
            //判断是否修改logo
            if(!empty($param['logo'])){
                $rel->logo = $param['logo'];
            }
            if(!$rel->is_apply && !$rel->is_vip){
                $rel->is_apply  = $param['checked'] ? 1 : 0;
                $rel->vip_title = $param['vip_title'];
                $rel->vip_about = $param['vip_about'];
            }
            $result = $rel->save();
        }else{
            $data['member_miniapp_id'] = $this->miniapp_id;
            $data['uid']                = $this->user->id;
            $data['is_apply']           = $param['checked'] ? 1 : 0;
            $data['is_vip']             = 0;
            $data['vip_title']          = $param['vip_title'];
            $data['vip_about']          = $param['vip_about'];
            $data['reg_time']           = time();
            $data['vip_time']           = time();
            $data['fans']               = AisInfoFollow::where(['uid' => $this->user->id])->count();            
            $data['logo']               = empty($param['logo']) ? $this->user->face: $param['logo'];
            $data['skin']               = empty($param['skin']) ? Config::get('upload.upload_relative').'static/ais/skin/2.jpg':$param['skin'];
            $result = AisInfoMp::create($data);
        }
        if($result){
            return enjson(200,'城市号设置成功');
        }
        return enjson(403,'设置失败');
    }

    /**
     * VIP认证
     */
    public function vipAuth(){
        if(request()->isPost()){
            $rel = AisInfoMp::where(['uid' => $this->user->id,'is_lock' => 0,'is_vip' => 1])->count();
            if($rel){
                return enjson(200,'认证用户',['vip'=>1]);
            }
        }
        return enjson(200,'非认证用户',['vip'=>0]);
    }

    /**
     * 商城图片
     */
    public function upImg(){
        if(request()->isPost()){
            $rel = Upload::index();
            if($rel['error'] == 0){
                return enjson(200,'success',$rel['url']);
            }else{
                return enjson(204);
            }
        }
    }
    
    /**
     * 发表信息
     */
    public function send(){  
        if(request()->isPost()){
            $param =  [
                'content'  => $this->request->param('content/s'),
                'telphone' => $this->request->param('telphone/s',''),
                'topday'   => $this->request->param('topday/d',0),
                'cate_id'  => $this->request->param('cate_id/d',0),
                'store_id' => $this->request->param('store_id/d',0),
                'imgs'     => $this->request->param('imgs/s','[]','htmlspecialchars_decode'),
                'fields'   => $this->request->param('fields/s','[]','htmlspecialchars_decode'),
                'is_get'   => $this->request->param('is_get/d',0),
                'price'    => $this->request->param('price/d'),
            ];
            $this->apiSign($param);
            $param['member_miniapp_id'] = $this->miniapp_id;
            $param['uid']               = $this->user->id;
            $validate = $this->validate($param,'Info.sendInfo');
            if(true !== $validate){
                return json(['code'=>403,'msg'=>$validate]);
            }
            $param['images'] = json_encode(Filter::filter_escape(json_decode($param['imgs'],true)));
            $param['fields'] = json_encode(Filter::filter_escape(json_decode($param['fields'],true)));
            //置顶
            $amount = 0;
            $config = AisConfig::getConfig($this->miniapp_id);
            if($param['topday'] && !empty($config)){
                $topday = json_decode($config->info,true);
                foreach ($topday as $value) {
                    if($value['day'] == $param['topday']){
                        $amount = $value['money'];
                        $param['topday'] = $value['day'];
                    }
                }
            }
            $param['top_money'] = $amount; //置顶金额
            $param['order_no']  = order_no($this->user->invite_code);
            $result = AisInfo::postThemes($param);
            if($result){
                if($amount > 0){
                    $order = [
                        'openid'     => $this->user['miniapp_uid'],
                        'miniapp_id' => $this->miniapp_id,
                        'name'       => '信息置顶',
                        'order_no'   => $param['order_no'],
                        'total_fee'  => $amount,
                        'notify_url' => api(1,'ais/notify/infoSend',$this->miniapp_id)
                    ];
                    if($this->member_miniapp->is_psp){
                        $setting = AisConfig::getConfig($this->miniapp_id);
                        if (empty($setting->mchid)) {
                            return enjson(403,'服务商模式下,必须配置默认商户号');
                        }
                        $order['mchid'] = $setting->mchid;  
                    }
                    $ispay = WechatPay::orderPay($order);;
                    if($ispay['code'] == 0){
                        return enjson(403,$ispay['msg']);
                    }
                    return enjson(200,'发布成功',$ispay['data']);
                }
                return enjson(204,'发布成功');
            }else{
                return enjson(403,'发布失败');
            }
        }
    }
    

    /**
     * 发布评论
     */
    public function postReply(){
        if(request()->isPost()){
            $param =  [
                'content'  => $this->request->param('content/s'),
                'info_id'  => $this->request->param('info_id/d'),
                'sign'     => $this->request->param('sign/s',0),
            ];
            $this->apiSign($param);
            $data = [
                'content'           => $param['content'],
                'info_id'           => $param['info_id'],
                'uid'               => $this->user->id,
                'member_miniapp_id' => $this->miniapp_id,
            ];
            $validate = $this->validate($data,'Info.sendReply');
            if(true !== $validate){
                return enjson(403,$validate);
            }
            $result =  AisInfoReply::postReply($data);
            if($result){
                AisInfo::where(['id' => $param['info_id']])->setInc('reply_num',1);
                return enjson(200,'评论成功');
            }else{
                return enjson(403,'评论失败');
            }
        }
    }



    /**
     * 点赞
     **/
    public function like(){
        $param['id']   = $this->request->param('id/d',0);
        $param['sign'] = $this->request->param('sign');
        $this->apiSign($param);
        $condition['member_miniapp_id'] = $this->miniapp_id;
        $condition['id']                = $param['id'];
        $rel = AisInfo::where($condition)->find();
        $like_face = json_decode(empty($rel->like_face) ? '[]':$rel->like_face,true);
        if(count($like_face) < 10){
            if(!in_array($this->user->face,$like_face)){
                array_push($like_face,$this->user->face);
                $rel->like_face = json_encode($like_face);
            }
        } 
        $rel->like = ['inc',1];
        $rel->save();
        if(empty($rel)){
            return enjson(403,'不用重复点赞');
        }else{
            return enjson(200);
        }
    }

    /**
     * 评论点赞
     * @return void
     */
    public function replylike(){
        $param['id']   = $this->request->param('id/d',0);
        $param['sign'] = $this->request->param('sign');
        $this->apiSign($param);
        $condition['member_miniapp_id'] = $this->miniapp_id;
        $condition['id']                = $param['id'];
        $rel = AisInfoReply::where($condition)->setInc('like',1);
        if(empty($rel)){
            return enjson(403,'不用重复点赞');
        }else{
            return enjson(200);
        }
    }
    /**
     * 关注或取消
     */
    public function follow(){
        $param['uid']   = $this->request->param('uid/d');
        $param['state'] = $this->request->param('state/d',0);
        $param['sign']  = $this->request->param('sign');
        $this->apiSign($param);
        if($param['uid'] == $this->user->id){
            return enjson(403,'不用关注自己');
        }
        //判断关注用户是否存在
        $is_user = SystemUser::where(['id' => $param['uid'],'is_lock' => 0,'is_delete' => 0])->find();
        if(empty($is_user)){
            return enjson(403,'当前用户已被封号');
        }
        //关注
        $condition['like_uid'] = $param['uid'];
        $condition['uid']      = $this->user->id;
        $info = AisInfoFollow::where($condition)->find();
        if(empty($info)){
            $follow = AisInfoFollow::where(['uid' => $this->user->id,'like_uid' => 0])->find();
            if($param['state'] == 1){
                if(empty($follow)){
                    $rel  = AisInfoFollow::create(['uid' => $this->user->id,'like_uid' => $param['uid']]);
                }else{
                    $follow->like_uid = $param['uid'];
                    $rel  = $follow->save();
                }
            }else{
                return enjson(403,'关注失败');
            }
        }else{
            if($param['state'] == 0){
                $info->like_uid = 0;
                $rel  = $info->save();
            }
        }
        if(empty($rel)){
            return enjson(403,'关注失败');
        }else{
            //增加粉丝
            $infomp = AisInfoMp::where(['uid' => $param['uid']])->find();
            if($infomp){
                if($param['state']){
                    $infomp->fans = ['inc',1];
                }else{
                    $infomp->fans = ['dec',1];
                }
                $infomp->save();
            }
            return enjson(200,$param['state']?'已关注':'取消关注');
        }
    }
}